package com.ocom.ugcapi.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.ocom.common.request.payhandle.QrCodeRefundRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.vo.pay.ServiceChargesVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.ugcapi.client.PayHandleClientService;
import com.ocom.ugcapi.service.PayService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Component
public class CheckWithholdRefundConsumer {

	@Resource
	RedisUtil redisUtil;

	@Autowired
	private PayHandleClientService payHandleClientService;

	@RabbitHandler
	@RabbitListener(queues = "dead-check-withhold-refund-queue")
	public void listenDelayQueue(Message message, @Headers Map<String, Object> headers, Channel channel) throws IOException {


//		String mqKey = "MqSimple:checkWithhold:"+ RandomUtil.getRandomString(20);


		System.out.println("测试代扣退款延时队列接收到消息:" + message);

		try {
//			Gson gson=new Gson();
//			String se = new String(message.getBody(), "UTF-8");
//			ServiceChargesVo serviceChargesVo = gson.fromJson(se, ServiceChargesVo.class);

			String fysms = new String(message.getBody(), StandardCharsets.UTF_8);

			//TODO 数据库操作样例
			log.info("serviceCharges-start:【{}】", fysms);


			if(fysms==null || fysms.length()>100){
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
				return;
			}

			Object requestRedis =  redisUtil.get(fysms);

			if(requestRedis==null){
				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
				return;
			}

			QrCodeRefundRequest qrCodeRefundRequest = (QrCodeRefundRequest)requestRedis;

			Result result = payHandleClientService.qrCodeRefund(qrCodeRefundRequest);

			log.info("测试代扣退款  参数 【{}】 返回 【{}】 ",qrCodeRefundRequest,result);

		}catch (Exception e){
			log.info("测试代扣退款队列异常 【{}】 ",e);
		}

		//确认接收消息
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}
}
